package com.stars.easyms.rest.handler;

import com.stars.easyms.base.constant.RestCodeConstants;
import com.stars.easyms.base.http.EasyMsResponseEntity;
import com.stars.easyms.feign.exception.BusinessFeignException;
import com.stars.easyms.rest.RestResponseHandler;
import com.stars.easyms.base.util.ExceptionUtil;
import com.stars.easyms.rest.exception.BusinessRestException;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;

/**
 * <p>className: DefaultRestResponseHandler</p>
 * <p>description: 默认的Rest响应处理类</p>
 *
 * @author guoguifang
 * @version 1.2.1
 * @date 2019-07-11 15:36
 */
public class EasyMsRestResponseHandler<T> implements RestResponseHandler<T> {

    /**
     * 处理成功返回消息
     *
     * @param output 返回参数
     * @return 返回消息
     */
    @NonNull
    @Override
    public EasyMsResponseEntity<T> handleRestResponse(@Nullable T output) {
        EasyMsResponseEntity<T> responseEntity = new EasyMsResponseEntity<>();
        responseEntity.setRetCode(RestCodeConstants.DEFAULT_SUCC_CODE);
        responseEntity.setBody(output);
        return responseEntity;
    }

    /**
     * 处理异常类型的返回消息
     *
     * @param t 异常信息
     * @return 返回消息
     */
    @NonNull
    @Override
    public EasyMsResponseEntity<T> handleRestResponseWithException(@NonNull Throwable t) {
        EasyMsResponseEntity<T> responseEntity = new EasyMsResponseEntity<>();
        if (t instanceof BusinessRestException) {
            BusinessRestException businessRestException = (BusinessRestException) t;
            responseEntity.setRetCode(businessRestException.getRetCode());
            responseEntity.setRetMsg(businessRestException.getRetMsg());
            responseEntity.setErrorDesc(businessRestException.getErrorDesc());
        } else if (t instanceof BusinessFeignException) {
            BusinessFeignException businessFeignException = (BusinessFeignException) t;
            responseEntity.setRetCode(businessFeignException.getRetCode());
            responseEntity.setRetMsg(businessFeignException.getRetMsg());
            responseEntity.setErrorDesc(businessFeignException.getErrorDesc());
        } else {
            responseEntity.setRetCode(RestCodeConstants.DEFAULT_ERROR_CODE);
            responseEntity.setRetMsg(RestCodeConstants.DEFAULT_ERROR_MSG);
            responseEntity.setErrorDesc(ExceptionUtil.getExceptionDesc(t));
        }
        return responseEntity;
    }

}